import React, {PropTypes} from 'react';
import {IndexLink, Link} from 'react-router';
import {Icon, Menu} from 'antd';
import _ from 'lodash';
import {app} from './app';
import redux from './_/redux';
import Home from './index/';
import Title from './title';
import {context} from './_';
import MenuBar from './index/menuBar';
import SelectLabel from './index/select';
import menus from './menus';
import ChangePasswordForm from './ChangePassword';
const t = (key, def) => {
    if (!key) return 'null';
    return def || key;
};

const icon = (name) => {
    if (!name) return;
    if (name.indexOf('fa-') >= 0) {
        return <i className={`fa ${name}`}/>;
    }
    return <i className={name}/>;
};

@context({
    routes: PropTypes.array
})

@redux('app', {
    actions: 'cfg',
    prefix: 'app'
})
@redux('app', {
    prefix: 'user',
    data: 'user',
    actions: 'logout'
})
export default class Index extends React.Component {
    constructor(props) {
        super(props);
        const {pathname: path = ''} = this.props.location;
        const k = _.last(path.split('/')).toLowerCase();
        const obj = _.find(menus, i => (_.findIndex(_.keys(i.items), i => i.toLowerCase() === k) >= 0)) || {};
        const root = obj.name === 'dict' ? `dict/${obj.cat}` : (obj.name || '');
        this.state = {
            menufold: false,
            current: [`${obj.name}${obj.cat ? `/${obj.cat}` : ''}/${k}`.toLowerCase()],
            openKeys: [root.toLowerCase(), `${root}/${k}`.toLowerCase()],
            ChangePasswordFormVisible: false
        };
    }

    componentDidMount() {
        //加载app设置
        let timer;
        $(window).on('resize.index', () => {
            clearTimeout(timer);
            timer = setTimeout(() => {
                const height = $(window).height();
                const width = $(window).width();
                const headHeight = $('#head').height();
                const mainHeight = height - headHeight;
                $('#main').height(mainHeight);
                this.props.appcfg({height, width, headHeight, mainHeight});
            }, 200);
        }).trigger('resize');
        this.props.appcfg({title: app.title});
    }

    componentWillUnmount() {
        $(window).off('resize.index');
    }

    onState = (flag, d1) => {
        switch (flag) {
        case 'menufold':
            this.setState({menufold: d1});
            break;
        }
    };
    onCancel = () => {
        this.setState({
            ChangePasswordFormVisible: false
        });
    };
    clickMenu = (e) => {
        this.setState({
            current: [e.key],
            openKeys: e.keyPath.slice(1)
        });
    };
    toggleMenu = (e) => {
        this.setState({
            openKeys: e.length > 1 ? e.slice(1) : e
        });
    };
    userClick = () => {
        this.setState({
            ChangePasswordFormVisible: true
        });
    };
    render() {
        const {userdata: user} = this.props;
        const {name = ''} = user || {};
        let menuOpts, menuStyle, leftStyle, rightStyle;
        const menuMini = 40;
        const menufold = this.state.menufold;
        if (menufold) {
            menuOpts = {};
            menuStyle = {width: menuMini};
            leftStyle = {width: menuMini};
            rightStyle = {paddingLeft: menuMini + 'px'};
        } else {
            menuStyle = {};
            menuOpts = {openKeys: this.state.openKeys};
            leftStyle = {};
            rightStyle = {};
        }
        return (
            <div id="app">
                <div id="head">
                    <div className="table">
                        <div className="row">
                            <div className="col middle">
                                <IndexLink to="/">
                                    <h1><Title/></h1>
                                </IndexLink>
                            </div>
                            <div className="col middle right">
                                <div className="selectLabelWrapper">
                                    <SelectLabel />
                                </div>
                                <span className="userInfo">
                                    <span onClick={this.userClick}>
                                        {name || '佚名'}<Icon type="user"/>
                                    </span>
                                    <span onClick={() => this.props.userlogout()}>
                                        退出<Icon type="poweroff"/>
                                    </span>
                                </span>
                                {/*<Button.Group className="userInfo">
                                    <Button onClick={this.userClick}>
                                        <Icon type="user"/>{name}
                                    </Button>
                                    <Button onClick={() => this.props.userlogout()}>
                                        <Icon type="poweroff"/>退出
                                    </Button>
                                </Button.Group>*/}
                            </div>
                        </div>
                        <ChangePasswordForm
                            onCancel={this.onCancel.bind(this)}
                            visible={this.state.ChangePasswordFormVisible ? this.state.ChangePasswordFormVisible : false}
                            title="修改密码"
                        />
                    </div>
                </div>
                <div id="main" className="scroll">
                    <div className="relative h100">
                        <div className="main-color layout-left" style={leftStyle}>
                            <MenuBar
                                fold={this.state.menufold}
                                onState={this.onState}
                            />
                            <Menu
                                id="newSidebar"
                                style={menuStyle}
                                mode={this.state.menufold ? 'vertical' : 'inline'}
                                onClick={this.clickMenu}
                                onOpenChange={this.toggleMenu}
                                selectedKeys={this.state.current}
                                {...menuOpts}
                            >
                                {menus.map(menu => {
                                    const mainKey = menu.name === "dict" ? `dict/${menu.cat}` : menu.name;
                                    return (
                                        <Menu.SubMenu
                                            key={mainKey.toLowerCase()}
                                            title={
                                                <span>{icon(menu.icon)}
                                                    <span>{menufold ? '' : t(menu.name, menu.title)}</span>
                                                </span>
                                            }
                                        >
                                            {menu.items && Object.keys(menu.items).map(m => {
                                                let key, path;
                                                if (menu.name === "dict") {
                                                    key = `dict/${menu.cat}/${m}`;
                                                    path = `/dict/${m}`;
                                                } else {
                                                    key = `${menu.name}/${m}`;
                                                    path = `/${m}`;
                                                }
                                                return (
                                                    <Menu.Item key={key.toLowerCase()}>
                                                        <Link to={path}>
                                                            {icon(m.icon)} {t(m, menu.items[m])}
                                                        </Link>
                                                    </Menu.Item>
                                                );
                                            })}
                                        </Menu.SubMenu>
                                    );
                                })}
                            </Menu>
                        </div>
                        <div className="layout-right" style={rightStyle}>
                            <div id="main-right" className="padding-l-r padding-b">{/*scroll-x*/}
                                {this.props.children || <Home/>}
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        );
    }
}
